package pers.andy.websocket.spring;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * 握手拦截器，用于处理请求携带参数
 * @author Andy.ye
 * @date 2018年3月29日 下午2:41:05
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
			String randStr = serverHttpRequest.getServletRequest().getParameter("randStr");
			String role = serverHttpRequest.getServletRequest().getParameter("role");
			if (StringUtils.isNotBlank(randStr)) {
				attributes.put("randStr", randStr);
			}
			if (StringUtils.isNotBlank(role)) {
				attributes.put("role", role);
			}
		}
		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
	}
}
